<template>
  <div style="position: relative">
    <div style="position: absolute; top:10px; right: 10px; z-index: 900">
      <el-button type="primary" icon="Delete" circle @click="clearPolygon"/>
      <el-button type="primary" circle @click="editPolygon">编辑</el-button>
      <el-button type="primary" circle @click="endEdit">结束</el-button>
    </div>
    <div id="container-rect" :style="{width,height}"></div>
  </div>
</template>

<script>
export default {
  name: 'GaodeMapRect',
  props: {
    modelValue: {
      type: String,
      default: undefined
    },
    // 线的颜色
    strokeColor: {
      type: String,
      default: 'red'
    },
    // 地图中心点
    center: {
      type: Array,
      default: () => {
        return [108.94878, 34.22259]
      }
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '790px'
    }
  },
  emits: ['update:modelValue'],
  data() {
    return {
      map: null, // 初始化 gMap 对象
      path: [],
      emitting: false,
      polygon: null,
      polygonEditors: null,
      isDrawing: true // 是否正在绘制多边形
    }
  },
  watch: {
    modelValue: {
      immediate: true,
      handler(val) {
        if (this.emitting) {
          return
        }
        console.log(val, 'val')
        // if (val) {
        //   this.location = JSON.parse(val)
        // } else {
        //   this.point = {}
        //   this.location = []
        // }
        if (val) {
          this.path = JSON.parse(val)
          this.$nextTick(() => {
            if (this.polygon) {
              this.map.remove(this.polygon)
            }
            this.polygon = new this.$AMap.Polygon({
              path: this.path,
              strokeColor: this.strokeColor, // 线条颜色
              strokeWeight: 3, // 线条宽度，默认为1
              strokeOpacity: 0.8, // 线条透明度
              fillOpacity: 0.35, // 填充透明度
              fillColor: '#1791fc', // 填充颜色
              zIndex: 50
            })
            // 多边形 polygon 对象添加到 Map
            this.map.add(this.polygon)
          })
        }

        // this.centerLocation = this.location
      }
    }
  },
  mounted() {
    // DOM初始化完成进行地图初始化
    this.initMap()
  },
  methods: {
    clearPolygon() {
      if (this.polygon) {
        this.map.remove(this.polygon)
        this.polygon = null
      }
      this.path = []
      // this.polygonEditors.close()
      this.initMap()
      this.isDrawing = true
    },

    editPolygon() {
      // this.initMap()
      const that = this
      if (this.path.length > 0) {
        this.map.plugin(['AMap.PolygonEditor'], function () {
          // 实例化多边形编辑器，传入地图实例和要进行编辑的多边形实例
          that.polygonEditors = new that.$AMap.PolygonEditor(that.map, that.polygon)
        })
      }
      if (this.polygonEditors) {
        this.polygonEditors.open()
      } else {
        console.log('PolygonEditor is not initialized')
      }
    },

    endEdit() {
      if (this.polygonEditors) {
        this.polygonEditors.close()
      }
      const newPath = this.polygon.getPath()
      console.log('更新后的多边形坐标:', newPath)
      this.path = newPath.map(item => {
        return [item.lng, item.lat]
      })
      this.$emit('update:modelValue', JSON.stringify(this.path))
      this.isDrawing = true
    },

    initMap() {
      const that = this
      that.map = new this.$AMap.Map('container-rect', { // 设置地图容器id
        viewMode: '2D', // 是否为3D地图模式
        zoom: 15, // 初始化地图级别
        doubleClickZoom: false, // 禁用双击缩放功能
        center: that.center // 初始化地图中心点位置
      })
      this.$AMap.plugin(['AMap.ToolBar'], (ToolBar) => {
        this.map.addControl(new this.$AMap.ToolBar())
        this.map.addControl(new this.$AMap.ControlBar({
          position: {
            right: '20px',
            top: '50px'
          },
          showControlButton: true // 是否显示倾斜、旋转按钮。默认为 true
        }))
      })

      // 只有在 path 数组不为空时才创建多边形
      if (this.path.length > 0) {
        that.polygon = new this.$AMap.Polygon({
          path: this.path,
          strokeColor: this.strokeColor, // 线条颜色
          strokeWeight: 3, // 线条宽度，默认为1
          strokeOpacity: 0.8, // 线条透明度
          fillOpacity: 0.35, // 填充透明度
          fillColor: '#1791fc', // 填充颜色
          zIndex: 50
        })
        // 多边形 polygon 对象添加到 Map
        that.map.add(that.polygon)

        that.map.plugin(['AMap.PolygonEditor'], function () {
          // 实例化多边形编辑器，传入地图实例和要进行编辑的多边形实例
          that.polygonEditors = new that.$AMap.PolygonEditor(that.map, that.polygon)
        })
      }

      // 监听地图点击事件
      that.map.on('click', this.handleClick)
    },

    handleClick(e) {
      if (this.isDrawing) {
        this.path.push([e.lnglat.lng, e.lnglat.lat])
        console.log('当前点击的坐标:', e.lnglat)
        if (this.polygon) {
          this.map.remove(this.polygon)
        }
        this.polygon = new this.$AMap.Polygon({
          path: this.path,
          strokeColor: this.strokeColor, // 线条颜色
          strokeWeight: 3, // 线条宽度，默认为1
          strokeOpacity: 0.8, // 线条透明度
          fillOpacity: 0.35, // 填充透明度
          fillColor: '#1791fc', // 填充颜色
          zIndex: 50
        })
        // 多边形 polygon 对象添加到 Map
        this.map.add(this.polygon)
      }
    }
  }
}
</script>

<style scoped lang="scss">
#container-rect {
  width: 100%;
  height: 790px;
  //margin: 100px auto;
  //border: 1px solid red;
}
</style>
